# -*- coding: utf-8 -*-
# Create on: 2019/9/3 11:26
# Author   : wukunan
"""
动态导入类
"""

import os
import importlib
import json


class DynamicClassLoader:
    """动态导入类"""
    def __init__(self):
        self.json_path = os.path.join(
            os.path.abspath(
                os.path.dirname(os.path.dirname(__file__))
            ),
            'conf/config.json')

    def load(self):
        # json配置文件解析
        tasks_dict = self._read_json_file(self.json_path)
        configs = {}
        # 解析文件
        for key, value in tasks_dict.items():
            # 实现动态import，解析module和class
            import_module = value['class_index']['module']
            import_class = value['class_index']['class']
            _module = importlib.import_module('.', import_module)
            import_module_class = getattr(_module, import_class)
            # 实现类和对应的实例参数及任务参数--具体参数格式业务自定义
            configs.setdefault(key, {"module_class": import_module_class,
                                     "parameters": value['parameters']})
        return configs

    @staticmethod
    def _read_json_file(path):
        with open(path, 'r', encoding='utf-8') as json_file:
            load_dict = json.load(json_file)
            return load_dict
